/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.cms.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.jinhe.tss.cms.dao.IArticleDao;
import com.jinhe.tss.cms.dao.IArticleRelationDao;
import com.jinhe.tss.cms.entity.Article;
import com.jinhe.tss.cms.entity.ArticleComment;
import com.jinhe.tss.cms.entity.ArticleScore;
import com.jinhe.tss.cms.entity.Channel;
import com.jinhe.tss.cms.service.IScoreService;
import com.jinhe.tss.component.support.persistence.pagequery.PageInfo;
import com.jinhe.tss.core.sso.Environment;
import com.jinhe.tss.core.util.EasyUtils;
import com.jinhe.tss.core.util.MathUtil;

public class ScoreService implements IScoreService {
	
    @Autowired private IArticleDao articleDao;
    @Autowired private IArticleRelationDao dao;

	public void saveScoreInfo(ArticleScore scorerObj) {
		dao.create(scorerObj);
		
        //修改文章总分
		Article article = articleDao.getEntity(scorerObj.getArticleId());
		article.setScores(MathUtil.addInteger(article.getScores(), scorerObj.getScore()));
		
        //修改文章打分总次数
		article.setScoreCount(MathUtil.addInteger(article.getScoreCount(), 1));
		dao.create(article);
	}
    
    public List<?> findScoreInfoBySelectedChannels(String channelList, Date startTime, Date endTime, String author) {
        if ( EasyUtils.isNullOrEmpty(channelList) ) {
            return new ArrayList<Object>();
        }
        dao.insertIds2TempTable(channelList.split(","));
        
        List<Long> articleIds = dao.getArticleIdList(startTime, endTime, author);
        
        dao.clearTempTable(); //先将上面插入的临时表数据清除
        dao.insertIds2TempTable((List<Long>) articleIds);
 
        String hql = "select count(*), a.score from ArticleScore a, Temp t where a.articleId = t.id group by a.score";
        return dao.getEntities(hql);
    }
    
    public Object[] findScoreInfoByArticle(Long articleId) {
        String hql = "select count(*), a.score from ArticleScore a where a.articleId = ? group by a.score";
        List<?> list = dao.getEntities(hql, articleId);
        
        String averageScore = "0.0";
        Article article = (Article) dao.getEntity(Article.class, articleId);
        if ( article.getScoreCount() != null) {
            double avg = article.getScores() / article.getScoreCount();
            averageScore = String.valueOf(avg);
        } 
        return new Object[]{list, averageScore};
    }

	public List<Object[]> findResult4Author(String channelList, Date startTime, Date endTime) {
        if ( EasyUtils.isNullOrEmpty(channelList) ) {
            return new ArrayList<Object[]>();
        }
        dao.insertIds2TempTable(channelList.split(","));
 
        List<Object[]> returnList = new  ArrayList<Object[]>();
		List<?> list = dao.getSummaryGroupByAuthor(startTime, endTime);
		for( Object temp : list ) {
			Object[] obj = (Object[]) temp;
			
			String author = (String)obj[0];
            if(author == null) continue;
            
            List<?> info = dao.getAverageScoreByAuthor(author, startTime, endTime);
			Object[] objInfo = (Object[]) info.get(0);
            Object[] returnObj = new Object[] { obj[0], objInfo[0], obj[1], obj[2], (Integer) objInfo[1] };
			returnList.add(returnObj);
		}
		return returnList;
	}
	
	public List<ArticleScore> getResult4Channel(Date startTime, Date endTime){
		List<ArticleScore> returnList = new  ArrayList<ArticleScore>();
		
		List<?> list = dao.getSummaryGroupByChannel(startTime, endTime);
		for( Object temp : list ) {
			Object[] objs = (Object[]) temp;
			Long channelId = (Long) objs[0];
			Channel channel = (Channel)dao.getEntity(Channel.class, channelId);
			Integer articleCount = dao.getChannelArtilceCount(channelId, startTime, endTime);
			
			ArticleScore scorer = new ArticleScore();
			scorer.setName(channel.getName());
			scorer.setHitCount(objs[1].toString());
			scorer.setArticleCount(String.valueOf(articleCount));
            
            List<?> info = dao.getAverageScoreByChannel(channelId, startTime,  endTime);
            Object [] objInfo = (Object[])info.get(0);
            scorer.setAverageScore( EasyUtils.convertObject2Integer(objInfo[0]).toString());
            scorer.setScoreCount( EasyUtils.convertObject2Integer(objInfo[1]).toString() );
            
			returnList.add(scorer);
		}
		return returnList;
	}

	/********************************************评论部分******************************************** */

	public void saveComments(Long articleId, String commentContent) {
		ArticleComment comment = new ArticleComment();
		comment.setArticleId(articleId);
		comment.setCommentContent(commentContent);
		comment.setCommentTime(new Date());
		comment.setCommenterName(Environment.getUserName());
		dao.create(comment);
	}

	public PageInfo getCommentListByArticle(Long articleId, Integer pageNum) {
        Article article = articleDao.getEntity(articleId);
        
		PageInfo page = dao.getCommentsList(articleId, pageNum == null ? new Integer(1) : pageNum);
		List<?> list = page.getItems();
		if( list != null && list.size() > 0 ) {
			for(int i = 0; i < list.size(); i++) {
				ArticleComment comment = (ArticleComment) list.get(i);
				comment.setArticleTitle(article.getTitle());
			}
		}
		return page;
	}

	public PageInfo searchCommentList(String keyword, Integer pageNum) {
		PageInfo page = dao.getCommentsList4Search(keyword, pageNum == null ? 1 : pageNum);
		List<?> list = page.getItems();
		if( !EasyUtils.isNullOrEmpty(list) ) {
			for( Object temp : list ){
				ArticleComment comment = (ArticleComment)temp;
				Article article = articleDao.getEntity(comment.getArticleId());
				comment.setArticleTitle(article.getTitle());
			}
		}
		return page;
	}
	
	public void delComments(Long commentsId) {
		dao.delete(ArticleComment.class, commentsId);
	}
}